<template>
  <div class="main">
    <el-card style="max-width: 50%">
      <template #header>
        <div class="card-header">
          <span>用户上传头像</span>
        </div>
      </template>
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input :value="useStore.username" disabled />
        </el-form-item>
        <el-form-item
          label="头  像"
          :label-width="formLabelWidth"
          prop="avatar"
        >
          <el-upload class="avatar-uploader" :before-upload="beforeUpload">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入用户小仓库
import useUserStore from '@/store/modules/user'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
// 引入接口
import { reqUploadAvatar } from '@/api/user/index'

let useStore = useUserStore() // 创建用户实例
// 获取用户ID与tokne
let userId = useStore.userId
let token = useStore.token
const formLabelWidth = '80px'
const avatarUrl = ref('')

const beforeUpload = async (file: any) => {
  // 创建了一个新的FormData对象，用户构建表单数据，并将file添加到FormData对象中
  const formData = new FormData()
  formData.append('avatar', file) // avatar是文件字段的名称，与后端接收图片参数相同
  // 发起post请求
  let res = await reqUploadAvatar(formData)
  if (res.code === 200) {
    ElNotification({
      message: res.msg,
      type: 'success',
    })
    setTimeout(() => {
      location.reload()
    }, 2000)
  } else {
    ElNotification({
      message: res.error_msg,
      type: 'error',
    })
  }
}
</script>

<style lang="scss" scoped>
.main {
  .card-header {
    text-align: center;
    font-size: 25px;
  }
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .avatar-uploader {
    display: inline-block;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    overflow: hidden;
  }
  .avatar {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 50%;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
